<template>
  <el-dialog v-model="dialogVisible" title="危险源设备位号选择" width="800">
    <div class="flex items-center justify-start mb-5">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter="handleQuery">
        <el-row :gutter="12" align="bottom">
          <el-col :span="7">
            <el-form-item label="设备名称">
              <el-input v-model="filters.deviceName" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="所属部门">
              <el-input v-model="filters.dept" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="设备位号">
              <el-input v-model="filters.deviceNum" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3" class="flex justify-end items-end gap-2">
            <el-button type="primary" :loading="queryLoading" @click="handleQuery">
              <el-icon class="mr-1">
                <Search />
              </el-icon>
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table ref="multipleTableRef" v-loading="tableLoading" :data="tableData" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
      <el-table-column property="deviceName" label="设备名称" width="150" />
      <el-table-column property="deviceNum" label="设备位号" width="200" />
      <el-table-column property="dept" label="所属部门" />
    </el-table>

    <template #footer>
      <div class="flex items-center justify-center">
        <el-button @click="onClose">
          <svg-icon icon-class="return" class="mr-2"></svg-icon>
          关闭
        </el-button>
        <el-button type="primary" @click="onSave">
          <svg-icon icon-class="save" class="mr-2"></svg-icon>
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { DeviceRow } from './constant';

const props = defineProps<{
  ids: number[];
}>();

// 搜索条件
const filters = reactive({
  deviceName: '',
  deviceNum: '',
  dept: ''
});

const emits = defineEmits(['changeSelectData']);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const selectData = ref<DeviceRow[]>([]);

// 表格
const multipleTableRef = ref(null);
const tableLoading = ref(false);
const queryLoading = ref(false);
const tableData = ref<DeviceRow[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 模拟数据
const allRecords = ref<DeviceRow[]>([
  {
    id: 100,
    deviceName: '设备名称',
    deviceNum: '设备位号',
    dept: '所属部门'
  },
  {
    id: 101,
    deviceName: '设备名称1',
    deviceNum: '设备位号1',
    dept: '所属部门1'
  },
  {
    id: 102,
    deviceName: '设备名称2',
    deviceNum: '设备位号2',
    dept: '所属部门2'
  }
]);

const dialogVisible = ref(false);

const handleQuery = () => {
  queryLoading.value = true;
  tableLoading.value = true;
  setTimeout(() => {
    refreshTable(getFilteredRecords());
    queryLoading.value = false;
    tableLoading.value = false;
  }, 200);
};

const getFilteredRecords = () => {
  return allRecords.value.filter((r) => {
    const m1 = filters.deviceName ? r.deviceName.includes(filters.deviceName) : true;
    const m2 = filters.deviceNum ? r.deviceNum.includes(filters.deviceNum) : true;
    const m3 = filters.dept ? r.dept.includes(filters.dept) : true;
    return m1 && m2 && m3;
  });
};

const refreshTable = (records: DeviceRow[]) => {
  pagination.total = records.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = records.slice(start, start + pagination.pageSize);
};

const handleSelectionChange = (selection: DeviceRow[]) => {
  selectData.value = selection;
};

const open = () => {
  dialogVisible.value = true;
  handleQuery();
};

const onSave = () => {
  emits('changeSelectData', selectData.value);
  onClose();
};
const onClose = () => {
  dialogVisible.value = false;
};

const toggleSelection = async () => {
  await nextTick();
  if (tableData.value?.length > 0 && props.ids?.length > 0) {
    tableData.value.forEach((row) => {
      if (props.ids.includes(row.id)) {
        multipleTableRef.value?.toggleRowSelection(row, true);
      }
    });
  } else {
    multipleTableRef.value?.clearSelection();
  }
};

watch(
  () => tableData.value,
  async () => {
    await toggleSelection();
  },
  { immediate: true }
);

defineExpose({ open });
</script>

<style scoped lang="scss"></style>
